import jsSHA from 'jssha'

function dec2hex(s) {
  return (s < 15.5 ? '0' : '') + Math.round(s).toString(16)
}

function hex2dec(s) {
  return parseInt(s, 16)
}

function base32tohex(base32) {
  var base32chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
  var bits = ''
  var hex = ''

  for (var i = 0; i < base32.length; i++) {
    var val = base32chars.indexOf(base32.charAt(i).toUpperCase())
    bits += leftpad(val.toString(2), 5, '0')
  }

  for (i = 0; i + 4 <= bits.length; i += 4) {
    var chunk = bits.substr(i, 4)
    hex = hex + parseInt(chunk, 2).toString(16)
  }

  return hex
}

function leftpad(str, len, pad) {
  if (len + 1 >= str.length) {
    str = new Array(len + 1 - str.length).join(pad) + str
  }
  return str
}

const generate = function (secret, epoch) {
  var key = base32tohex(secret)

  // HMAC generator requires secret key to have even number of nibbles
  if (key.length % 2 !== 0) {
    key += '0'
  }

  // If no time is given, set time as now
  if (typeof epoch === 'undefined') {
    epoch = Math.round(new Date().getTime() / 1000.0)
  }
  var time = leftpad(dec2hex(Math.floor(epoch / 30)), 16, '0')
  //   console.log(time)
  const hmacObj = new jsSHA('SHA-1', 'HEX', { hmacKey: { value: key, format: 'HEX' } })
  hmacObj.update(time)
  var hmac = hmacObj.getHMAC('HEX')
  //   console.log('jsSHA', hmac)

  var offset = 0
  if (hmac !== 'KEY MUST BE IN BYTE INCREMENTS') {
    offset = hex2dec(hmac.substring(hmac.length - 1))
  }

  var otp = ((hex2dec(hmac.substr(offset * 2, 8)) & hex2dec('7fffffff')) % 1000000) + ''
  return Array(7 - otp.length).join('0') + otp
}

export default { generate }
